import { editTypes } from './../../../config/content-type'
import { Component, Vue } from 'vue-property-decorator'

@Component
export default class Sse extends Vue {
  url = '/api/document/sse/subscribe'

  source: EventSource | null = null

  connect (): Promise<Event> {
    const url = this.url + '/' + Vue.prototype.$auth?.principle?.user?.id
    const source = new EventSource(url)
    this.source = source
    return new Promise((resolve, reject) => {
      source.onopen = (data: Event) => {
        console.info('sse 连接成功')
        resolve(data)
      }
      source.onerror = (data: Event) => {
        console.error('sse 连接失败')
        reject(data)
      }
      source.onmessage = (event: MessageEvent) => {
        const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data
        if (Object.prototype.toString.call(data) === '[object Object]') {
          const name = data.category + ':' + data.type
          this.$emit(name, data)
          this.$emit('*', data)
        }
      }
    })
  }

  on (name: string | string[], fn: (data: any) => void) {
    this.$on(name, fn)
  }

  off (name?: string | string[], fn?: (...args: any[]) => void) {
    this.$off(name, fn)
  }

  close () {
    this.$off()
    if (this.source) this.source.close()
  }
}
